package xyz.xtt.asset.utils.pay;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author zhangcj
 * @date 2025/2/8 14:25
 */
@Slf4j
public class HttpsUtils {

    public static String post(String url, Object request) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(new BasicCredentialsProvider()).build();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        ObjectMapper objectMapper = new ObjectMapper();
        post.setEntity(new StringEntity(objectMapper.writeValueAsString(request), ContentType.create("application/json", "utf-8")));
        System.out.println("请求入参:" + objectMapper.writeValueAsString(request));
        CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(post);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            String result = EntityUtils.toString(response.getEntity());
            log.info("200请求结果:{}", result);
            return result;

        }else if (response != null && response.getStatusLine().getStatusCode() == 500) {
            String result = EntityUtils.toString(response.getEntity());
            log.info("500请求结果:{}", result);
            return result;
        }
        return null;
    }

}
